import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AdminEntity } from 'src/admin/admin.entity';
import { Repository } from 'typeorm';
import { UserLogin, User } from './user.interface';
import * as argon2 from 'argon2';
import { AuthService } from 'src/auth/auth.service';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(AdminEntity)
    private adminRespository: Repository<AdminEntity>,
    private authService: AuthService,
  ) {}

  async login({ username, password }: UserLogin) {
    const user = await this.adminRespository.findOne({ username });

    if (!user) {
      return {
        code: 404,
        message: '用户不存在',
      };
    }

    if (await argon2.verify(user.password, password || '')) {

      // 生成token
      return {
        code: 200,
        message: '成功',
        data: {
          token: this.authService.generateJwt(user),
        }
      };
    }

    return {
      code: 400,
      message: '密码错误',
    };
  }
}
